//
//  ACLiveCreateViewController.m
//  ACLiteAVUISDK
//
//  Created by 冯琰琰 on 2021/3/30.
//

#import "ACLiveCreateViewController.h"
#import "ACCreateLiveInfoCell.h"
#import "ACLiveFileListViewController.h"
#import "ACLiveInfoEditViewController.h"
#import "CXDatePickerView.h"
#import <Photos/PHPhotoLibrary.h>

@interface ACLiveCreateViewController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property(nonatomic,strong)UITableView *tableview;
@property(nonatomic,strong)NSMutableArray<NSDictionary *> *array;
@property(nonatomic,strong)TRTCLiveRoom *liveRoom;
@property(nonatomic,copy)NSString *startTime;
@property(nonatomic,copy)NSString *endTime;
@property(nonatomic,copy)NSString *isRecord;
@property(nonatomic,copy)NSString *live_title;
@property(nonatomic,copy)NSString *live_cover;
@property(nonatomic,copy)NSString *isNeedPwd;
@property(nonatomic,copy)NSString *pwdStr;
@property(nonatomic,strong)UIImagePickerController *picker;
@property(nonatomic,strong)UIButton *uploadBtn;
@property(nonatomic,copy)NSString *info_title;
@property(nonatomic,copy)NSString *info_cover;
@property(nonatomic,copy)NSString *info_desc;
@property(nonatomic,strong)NSMutableArray *selectedArray;

@end

@implementation ACLiveCreateViewController
-(UITableView *)tableview{
    if (!_tableview) {
        _tableview = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.estimatedRowHeight = 70;
        _tableview.backgroundColor = [UIColor whiteColor];
        NSBundle *curB = [NSBundle BundleWithBundleName:ACLiteAVUISDK targetClass:[self class] ];
        [_tableview registerNib:[UINib nibWithNibName:@"ACCreateLiveInfoCell" bundle:curB] forCellReuseIdentifier:@"ACCreateLiveInfoCell"];
        _tableview.tableFooterView = [UIView new];
    }
    return _tableview;
}
-(NSMutableArray *)selectedArray{
    if (!_selectedArray) {
        _selectedArray = [NSMutableArray array];
    }
    return _selectedArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"新建直播";
    self.view.backgroundColor = UIColorFromRGB(0xF4F5F8);
    self.isNeedPwd = @"0";
    self.isRecord = @"0";
    // rightType   0 空白  1 箭头 2 上传按钮  3 switch
    // action  1 编辑  2跳转页面 3时间选择器  4上传按钮  5 switch
    self.array = [[NSMutableArray alloc] initWithObjects:@{@"title":@"路演主题",@"rightType":@"0",@"Info":@"",@"action":@"1",@"placeHolder":@"请输入路演主题"},@{@"title":@"路演简介",@"rightType":@"1",@"Info":@"请输入路演简介",@"action":@"2",@"placeHolder":@""},@{@"title":@"开始时间",@"rightType":@"1",@"Info":@"",@"action":@"3",@"placeHolder":@"请设置开始时间"},@{@"title":@"结束时间",@"rightType":@"1",@"Info":@"",@"action":@"3",@"placeHolder":@"请设置结束时间"},@{@"title":@"上传文档",@"rightType":@"2",@"Info":@"",@"action":@"4",@"placeHolder":@""},@{@"title":@"开启录制",@"rightType":@"3",@"Info":self.isRecord,@"action":@"5",@"placeHolder":@""},@{@"title":@"开启密码",@"rightType":@"3",@"Info":self.isNeedPwd,@"action":@"5",@"placeHolder":@""},@{@"title":@"密码",@"rightType":@"0",@"Info":@"",@"action":@"1",@"placeHolder":@"请输入密码"}, nil];
    
    UIView *bgView = [[UIView alloc] init];
    bgView.backgroundColor = UIColorFromRGB(0xffffff);
    bgView.layer.shadowColor = UIColorFromRGB(0xEAEBEE).CGColor;
    bgView.layer.shadowOffset = CGSizeMake(0,-1);
    bgView.layer.shadowOpacity = 1;
    bgView.layer.shadowRadius = 4;
    
    [self.view addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(0);
        make.height.mas_equalTo(ACSafeAreaBottomHeight+ 68);
    }];
    
    UIButton *createBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [createBtn.titleLabel setFont:[UIFont systemFontOfSize:16.0 weight:UIFontWeightMedium]];
    [createBtn setTitle:@"预约路演" forState:UIControlStateNormal];
    [createBtn setBackgroundColor:UIColorFromRGB(0xFF6048)];
    [createBtn setTitleColor:UIColorFromRGB(0xffffff) forState:UIControlStateNormal];
    createBtn.layer.masksToBounds = YES;
    createBtn.layer.cornerRadius = 24;
    [self.view addSubview:createBtn];
    [createBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-(ACSafeAreaBottomHeight + 10));
        make.height.mas_equalTo(48);
        make.left.mas_offset(48);
        make.right.mas_offset(-48);
    }];
    @weakify(self);
    [[createBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        [self creteRoadShowLive];
    }];
    
    UIView *headerBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 80)];
    headerBgView.backgroundColor = UIColorFromRGB(0xffffff);
    [self.view addSubview:headerBgView];
    
    self.uploadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.uploadBtn.layer.masksToBounds = YES;
    self.uploadBtn.layer.cornerRadius = 4;
    [self.uploadBtn setImage:[UIImage imageWithName:@"icon_live_cover" bundle:ACLiteAVUISDK targetClass:[self class]] forState:UIControlStateNormal];
    [headerBgView addSubview:self.uploadBtn];
    [self.uploadBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(116, 65));
        make.top.mas_equalTo(15);
        make.bottom.mas_equalTo(0);
    }];
    [[self.uploadBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        // 上传图片
        [self showImagePicker];
    }];
    self.tableview.tableHeaderView = headerBgView;
    
    [self.view addSubview:self.tableview];
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(bgView.mas_top);
        make.top.mas_equalTo(10);
        make.left.right.mas_equalTo(0);
    }];
}
-(void)creteRoadShowLive{
    if (self.live_title.length == 0 || self.live_title == nil) {
        [SVProgressHUD showInfoWithStatus:@"请输入路演主题"];
        return ;
    }
    if (self.live_cover.length == 0 || self.live_cover == nil) {
        [SVProgressHUD showInfoWithStatus:@"请上传路演封面"];
        return;
    }
    if (self.startTime.length == 0 || self.startTime == nil) {
        [SVProgressHUD showInfoWithStatus:@"请设置路演开始时间"];
        return;
    }
    if (self.endTime.length == 0 || self.endTime == nil) {
        [SVProgressHUD showInfoWithStatus:@"请设置路演结束时间"];
        return;;
    }
    if ([self.isNeedPwd boolValue]) {
        if (self.pwdStr.length == 0 || self.pwdStr == nil) {
            [SVProgressHUD showInfoWithStatus:@"请设置路演观看密码"];
            return;;
        }
    }
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:@{@"title":self.live_title,@"img":self.live_cover,@"start_time":self.startTime,@"end_time":self.endTime,@"enable_recording":self.isRecord,@"enable_password":self.isNeedPwd}];
    if ([self.isNeedPwd boolValue]) {
        [params setValue:self.pwdStr forKey:@"password"];
    }
    if (self.info_title.length != 0) {
        [params setValue:self.info_title forKey:@"intro_title"];
    }
    if (self.info_desc.length != 0) {
        [params setValue:self.info_desc forKey:@"intro_desc"];
    }
    if (self.info_cover.length != 0) {
        [params setValue:self.info_cover forKey:@"intro_img"];
    }
    if (self.selectedArray.count != 0 ) {
        [params setValue:self.selectedArray forKey:@"documents"];
    }
    [ACLiveRoomManager requestCreateRoadShowWitchInfo:params requestCallback:^(int code, NSString * _Nullable message) {
        if (code == 0) {
            @weakify(self)
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"预约提醒" message:@"预约成功！等待审核中，审核成功之后可在预约列表开始" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                @strongify(self)
                [self.navigationController popViewControllerAnimated:YES];
            }];
            [alertVC addAction:sureAction];
            [self presentViewController:alertVC animated:YES completion:nil];
        }
    }];
}
-(void)showImagePicker{
    @weakify(self)
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"上传封面" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancelBtn = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
       // 从相册选取
        @strongify(self)
        [self chooseFromAlbum];
    }];
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
       // 拍照
        @strongify(self)
        [self takePhoto];
    }];
    [alertVC addAction:cancelBtn];
    [alertVC addAction:albumAction];
    [alertVC addAction:cameraAction];
    [self presentViewController:alertVC animated:YES completion:nil];
}

-(void)takePhoto{
//    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
//    if (status == PHAuthorizationStatusDenied || status == PHAuthorizationStatusRestricted) {
//        // 没有权限
//        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"请在iPhone的设置-隐私-相机中允许访问相机" preferredStyle:UIAlertControllerStyleActionSheet];
//        UIAlertAction *cancelBtn = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//        }];
//        [alertVC addAction:cancelBtn];
//        [self presentViewController:alertVC animated:YES completion:nil];
//    }else if (status == PHAuthorizationStatusNotDetermined){
//        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
//            if (granted) {
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    [self takePhoto];
//                });
//            }
//        }];
//    }else{
        // 有权限
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            self.picker = [[UIImagePickerController alloc] init];
            [self.picker setSourceType:UIImagePickerControllerSourceTypeCamera];
            [self.picker setAllowsEditing:YES];
            [self.picker setDelegate:self];
            [self presentViewController:self.picker animated:YES completion:nil];
        }else{
            DDLogInfo(@"照片源不可用");
        }
//    }
}
-(void)chooseFromAlbum{
//    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
//    if (status == PHAuthorizationStatusDenied || status == PHAuthorizationStatusRestricted) {
//        // 没有权限
//        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"请在iPhone的设置-隐私-相册中允许访问相册" preferredStyle:UIAlertControllerStyleActionSheet];
//        UIAlertAction *cancelBtn = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//        }];
//        [alertVC addAction:cancelBtn];
//        [self presentViewController:alertVC animated:YES completion:nil];
//    }else if (status == PHAuthorizationStatusNotDetermined){
//        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
//            if (granted) {
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    [self takePhoto];
//                });
//            }
//        }];
//    }else{
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            self.picker = [[UIImagePickerController alloc] init];
            [self.picker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
            [self.picker setAllowsEditing:YES];
            [self.picker setDelegate:self];
            [self presentViewController:self.picker animated:YES completion:nil];
        }else{
            DDLogInfo(@"照片源不可用");
        }
//    }
}
-(void)showDatePickerForStart:(BOOL)isStart{
    @weakify(self);
    CXDatePickerView *datepicker = [[CXDatePickerView alloc] initWithDateStyle:CXDateMonthDayHourMinute completeBlock:^(NSDate *selectDate) {
        @strongify(self)
        NSString *dateString = [selectDate wgk_stringWithFormat:@"yyyy-MM-dd HH:mm"];
        NSDictionary *dic;
        if (isStart) {
            if ([dateString isEqualToString:self.endTime]) {
                [SVProgressHUD showInfoWithStatus:@"开始时间要早于结束时间"];
                return ;
            }
            self.startTime = dateString;
            dic = @{@"title":@"开始时间",@"rightType":@"1",@"Info":self.startTime,@"action":@"3",@"placeHolder":@"请设置开始时间"};
            [self.array replaceObjectAtIndex:2 withObject:dic];
        }else{
            if ([dateString isEqualToString:self.startTime]) {
                [SVProgressHUD showInfoWithStatus:@"结束时间要晚于开始时间相同"];
                return ;
            }
            if ([dateString isEqualToString:[[NSDate date] wgk_stringWithFormat:@"yyyy-MM-dd HH:mm"]]) {
                [SVProgressHUD showInfoWithStatus:@"结束时间要晚于当前时间"];
                return ;
            }
            self.endTime = dateString;
            dic = @{@"title":@"结束时间",@"rightType":@"1",@"Info":self.endTime,@"action":@"3",@"placeHolder":@"请设置结束时间"};
            [self.array replaceObjectAtIndex:3 withObject:dic];
        }
        [self.tableview reloadData];
        DDLogInfo(@"选择的日期：%@",dateString);
    }];
    datepicker.dateUnitLabelColor = UIColorFromRGB(0xFF6048);//年-月-日-时-分-秒 颜色
    datepicker.datePickerColor = [UIColor blackColor];//滚轮日期颜色
    datepicker.headerViewColor = UIColorFromRGB(0xFF6048); // 顶部视图背景颜色
    datepicker.doneButtonColor = [UIColor whiteColor]; // 确认按钮字体颜色
    datepicker.cancelButtonColor = [UIColor whiteColor]; // 取消按钮颜色
    datepicker.shadeViewAlphaWhenShow = 0.25;
    datepicker.headerTitle = @"选择日期";
    datepicker.headerTitleColor = [UIColor whiteColor];
    if (isStart) {
        datepicker.minLimitDate = [NSDate date];
    }else{
        if ([self.startTime isEqualToString:@""] || self.startTime == nil) {
            datepicker.minLimitDate = [[NSDate date] wgk_dateByAddingMinutes:30];
        }else{
            datepicker.minLimitDate = [[NSDate wgk_dateWithString:self.startTime format:@"yyyy-MM-dd HH:mm"] wgk_dateByAddingMinutes:30];
        }
    }
    if (isStart) {
        if ([self.endTime isEqualToString:@""] || self.endTime == nil) {
            datepicker.maxLimitDate = [NSDate wgk_dateWithString:@"2221-04-12 00:00" format:@"yyyy-MM-dd HH:mm"];
        }else{
            datepicker.maxLimitDate = [[NSDate wgk_dateWithString:self.endTime format:@"yyyy-MM-dd HH:mm"] wgk_dateBySubtractingMinutes:30];
        }
    }else{
        datepicker.maxLimitDate = [NSDate wgk_dateWithString:@"2221-01-01 00:00" format:@"yyyy-MM-dd HH:mm"];
    }
    datepicker.datePickerSelectColor = UIColorFromRGB(0xFF6048);
    datepicker.datePickerSelectFont = [UIFont systemFontOfSize:17];
    datepicker.yearLabelColor = [UIColor whiteColor];
    [datepicker show];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([self.isNeedPwd isEqualToString:@"0"]) {
        return self.array.count - 1;
    }else{
        return self.array.count;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ACCreateLiveInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ACCreateLiveInfoCell" forIndexPath:indexPath];
    if (!cell) {
        cell = [[ACCreateLiveInfoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ACCreateLiveInfoCell"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.dataDic = self.array[indexPath.row];
    @weakify(self);
    cell.switchValueChangeHandler = ^(BOOL isOn) {
        NSDictionary *dic = [NSDictionary dictionary];
        if (indexPath.row == 5) {
            // 录制开关
            self.isRecord = [NSString stringWithFormat:@"%d",isOn];
            dic =  @{@"title":@"开启录制",@"rightType":@"3",@"Info":self.isRecord,@"action":@"5",@"placeHolder":@""};
           
        }else if (indexPath.row == 6){
            // 密码开关
            self.isNeedPwd = [NSString stringWithFormat:@"%d",isOn];
            dic = @{@"title":@"开启密码",@"rightType":@"3",@"Info":self.isNeedPwd,@"action":@"5",@"placeHolder":@""};
        }
        [self.array replaceObjectAtIndex:indexPath.row withObject:dic];
        [self.tableview reloadData];
    };
    cell.uploadClickHandler = ^{
        @strongify(self)
      // 上传事件
        ACLiveFileListViewController *fileListVC = [[ACLiveFileListViewController alloc] init];
        fileListVC.index = 3;
        [fileListVC getFiles];
        fileListVC.selectedArray = self.selectedArray;
        fileListVC.selectedHandler = ^(NSArray * _Nonnull fileIdArray) {
            DDLogInfo(@"%@",fileIdArray);
            [self.selectedArray addObjectsFromArray:fileIdArray];
        };
        [self.navigationController pushViewController:fileListVC animated:YES];
    };
    cell.textEditEndHandler = ^(NSString * _Nonnull text) {
        @strongify(self)
        NSDictionary *dic = [NSDictionary dictionary];
        if (indexPath.row == 0) {
            // 路演标题
            self.live_title = text;
            dic = @{@"title":@"路演主题",@"rightType":@"0",@"Info":self.live_title,@"action":@"1",@"placeHolder":@"请输入路演主题"};
        }else if (indexPath.row == self.array.count - 1){
            self.pwdStr = text;
            dic = @{@"title":@"密码",@"rightType":@"0",@"Info":self.pwdStr,@"action":@"1",@"placeHolder":@"请输入密码"};
        }
        [self.array replaceObjectAtIndex:indexPath.row withObject:dic];
        [self.tableview reloadData];
    };
    return  cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *dataDic = self.array[indexPath.row];
    NSInteger actionType = [[dataDic valueForKey:@"action"] integerValue];
    // action  1 编辑  2跳转页面 3时间选择器  4上传按钮  5 switch
    if (actionType == 2) {
        @weakify(self)
        ACLiveInfoEditViewController *infoEditVC = [[ACLiveInfoEditViewController alloc] init];
        infoEditVC.finishedHandler = ^(NSString * _Nonnull info_title, NSString * _Nonnull info_Image, NSString * _Nonnull info_desc) {
            @strongify(self)
            self.info_title = info_title;
            self.info_cover = info_Image;
            self.info_desc = info_desc;
        };
        infoEditVC.info_cover = self.info_cover;
        infoEditVC.info_title = self.info_title;
        infoEditVC.info_desc = self.info_desc;
        [self.navigationController pushViewController:infoEditVC animated:YES];
    }else if (actionType == 3){
        [self showDatePickerForStart:(indexPath.row == 2)];
    }
}
#pragma mark - UIImagePickerControllerDelegate UINavigationControllerDelegate
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
   [picker dismissViewControllerAnimated:YES completion:nil];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info{
    NSString* type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        UIImage* edit = [info objectForKey:UIImagePickerControllerEditedImage];
        NSData *imageData = UIImagePNGRepresentation(edit);
        CIImage *ciiimage = [CIImage imageWithData:imageData];
        CIContext *context = [CIContext context];
        if (@available(iOS 10.0, *)) {
            NSData *jpgData = [context JPEGRepresentationOfImage:ciiimage colorSpace:[ciiimage colorSpace] options:[NSDictionary dictionary]];
            UIImage *image = [UIImage imageWithData:jpgData];
            NSData *data_upload = UIImageJPEGRepresentation(image, 0.1);
            [SVProgressHUD showWithStatus:@"正在上传"];
            [ACLiveRoomManager uploadImageWithImageData:data_upload success:^(id  _Nonnull responseObject) {
                DDLogInfo(@"%@",responseObject);
                dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD showSuccessWithStatus:@"上传完成"];
                });
                self.live_cover = [responseObject objectForKey:@"file_url"];
                [self.uploadBtn setImage:image forState:UIControlStateNormal];
            }];
        } else {
            // Fallback on earlier versions
        }
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}
@end
